<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="orderNo">
              <el-input v-model="filters.orderNo" clearable placeholder="订单编号"></el-input>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-select v-model="filters.businessId" placeholder="请选择商户" clearable filterable>
                <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="orderSplitState">
              <el-select v-model="filters.orderSplitState" placeholder="请选择分账状态" clearable filterable>
                <el-option v-for="item in orderSplitStateList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="date">
              <el-date-picker v-model="filters.date" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
            <el-form-item>
              <div class="amount-wrapper">
                <el-input type="number" v-model="filters.minSplitAmount" placeholder="最少金额"> </el-input>
                <div class="separate"></div>
                <el-input type="number" v-model="filters.maxSplitAmount" placeholder="最多金额"> </el-input>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button v-has="permissionExport" plain type="success" icon="el-icon-folder" size="mini" @click="handleExport()">导出</el-button>
            <el-button v-has="permissionReset" plain type="primary" icon="el-icon-menu" size="mini" @click="handleResetSplitOrder()">重置订单分账</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
        ref="tableList"
        :data="dataList"
        :fit="true"
        highlight-current-row
        v-loading="listLoading"
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据"
        @row-click="$refs.tableList.toggleRowSelection($event)"
        @selection-change="handleSelectChange"
      >
        <el-table-column type="selection" label="序号" width="50" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>

        <el-table-column label="订单编号" prop="orderNo" align="center" width="140"> </el-table-column>
        <el-table-column label="商户" prop="businessName" align="center" width="140"> </el-table-column>
        <el-table-column label="服务员" prop="waiterName" align="center" width="140"> </el-table-column>
        <el-table-column label="二级推广员" prop="promoterName" align="center" width="140"> </el-table-column>
        <el-table-column label="一级推广员" prop="firstPromoterName" align="center" width="140"> </el-table-column>

        <el-table-column label="业务员" prop="saleName" align="center" width="140"> </el-table-column>
        <el-table-column label="公司商户" prop="companyBusinessName" align="center" width="140"> </el-table-column>
        <el-table-column label="分账金额" prop="splitAmount" align="center" width="140"> </el-table-column>

        <el-table-column label="商户收益金额+" prop="businessGain" align="center" width="140">
          <template slot-scope="scope">
            <div>
              {{ scope.row.businessGain }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商户补贴金额-" prop="businessOut" align="center" width="140">
          <!-- （配送费/活动费） -->
          <template slot-scope="scope">
            <div>
              {{ scope.row.businessOut }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="分账状态">
          <template slot-scope="scope">
            <el-tag effect="dark" size="mini" :type="formatOrderSplitStates(scope.row.orderSplitState)">
              {{ formatOrderSplitState(scope.row.orderSplitState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="createDate" align="center" width="170"> </el-table-column>
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <!-- <el-dropdown>
                            <el-dropdown-menu slot="dropdown">
                                <el-drop-item>

                                </el-drop-item>
                            </el-dropdown-menu>

                        </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>
<script>
import OrderSplitApi from '@/api/account/orderSplit.js';
import * as message from '@/constants/message';
import BusinessApi from '@/api/business/business';
import fileDownload from 'js-file-download';
export default {
  name: 'OrderSplitManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      listLoading: true,
      filters: {
        orderNo: '',
        date: [],
        businessId: '',
        minSplitAmount: '',
        maxSplitAmount: '',
        orderSplitState: '',
      },
      orderSplitStateList: [
        { value: 1, label: '分账中' },
        { value: 2, label: '分账中(部分成功)' },
        { value: 3, label: '分帐中(存在失败)' },
        { value: 4, label: '分账结束(存在失败)' },
        { value: 5, label: '分账完成' },
      ],
      businessList: [],
      selectedRows: [],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      permissionCheck: 'SYSTEM_MANAGER_ACCOUNT_ORDER_SPLIT_LIST_SEE',
      permissionExport: 'SYSTEM_MANAGER_ACCOUNT_ORDER_SPLIT_LIST_EXPORT',
      permissionReset: 'SYSTEM_MANAGER_ACCOUNT_ORDER_SPLIT_LIST_RESET',

    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listLoading = true;
      this.listData();
      this.getBusinessList();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then((res) => {
        this.businessList = res.data;
      });
    },
    // 导出
    async handleExport() {
      const { businessId, minSplitAmount, maxSplitAmount, date } = this.filters;
      if (!businessId) {
        this.$message.error('请选择商户');
        return;
      }
      const params = {
        businessId,
        minSplitAmount,
        maxSplitAmount,
        beginDate: date[0] || '',
        endDate: date[1] || '',
      };
      const res = await OrderSplitApi.splitExcel(params);
      fileDownload(res, '分账列表.xlsx');
    },
    handleSelectChange(rows) {
      this.selectedRows = rows;
    },
    // 重置订单分账
    async handleResetSplitOrder() {
      const { selectedRows } = this;
      if (selectedRows.length == 0) {
        this.$message.error('至少选择一项数据');
        return false;
      }

      await this.$confirm('确定重置订单分账吗？', '提示', {});
      const params = {
        state: 1,
        ids: selectedRows.map((item) => item.orderId),
      };
      await OrderSplitApi.resetSplit(params);
      this.onSearch();
      this.$Utils.notifySuccess();
    },
    formatOrderSplitState(val) {
      switch (val) {
        case 1:
          return '分帐中';
        case 2:
          return '分账中(部分成功)';
        case 3:
          return '分账中(存在失败)';
        case 4:
          return '分账结束(存在失败)';
        case 5:
          return '分账完成';
      }
    },
    formatOrderSplitStates(val) {
      switch (val) {
        case 1:
          return '';
        case 2:
          return 'info';
        case 3:
          return 'warning';
        case 4:
          return 'danger';
        case 5:
          return 'success';
      }
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listData();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listData();
    },
    handleClickDetail(row) {
      this.$router.push({
        path: '/account/orderSplitDetail',
        query: { id: row.orderSplitId },
      });
    },
    resetForm() {
      this.filters.minSplitAmount = '';
      this.filters.maxSplitAmount = '';
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      const { date, orderNo, minSplitAmount, maxSplitAmount, businessId, orderSplitState } = this.filters;
      if (minSplitAmount > 0 && maxSplitAmount > 0 && parseFloat(minSplitAmount) > parseFloat(maxSplitAmount)) {
        this.$message.error('最大金额必须大于最小金额');
        return;
      }
      // 获取列表数据
      let cond = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        orderNo,
        beginDate: date[0] || '',
        endDate: date[1] || '',
        minSplitAmount,
        maxSplitAmount,
        businessId,
        orderSplitState,
      };
      this.listLoading = true;
      OrderSplitApi.orderSplitList(cond)
        .then((res) => {
          this.dataList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.listLoading = false;
          this.$refs.table.bodyWrapper.scrollTop = 0;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.amount-wrapper {
  display: flex;
  align-items: center;

  .el-input {
    width: 200px;
  }

  .el-input,
  .separate {
    flex-shrink: 0;
  }

  .separate {
    width: 14px;
    height: 2px;
    margin: 0 4px;
    background-color: #dcdfe6;
  }
}
</style>
